﻿using Inspinia_MVC5.Data;
using Inspinia_MVC5.Models;
using SeniOA.MVC;
using System;
using System.Data.Entity;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Webdiyer.WebControls.Mvc;

namespace Inspinia_MVC5.Controllers
{

    public class AdminsController : Controller
    {
        private BooksSystemContext db = new BooksSystemContext();
        public static string VerifyURL = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/verify";

        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(string username,string password)
        {
            if (Session["ValidateCode"] == null)
            {
                return View();

            }
            string code = Session["ValidateCode"].ToString();
            if (Request.Form["ValidateCodes"].ToString() != code)
            {
                ModelState.AddModelError("", "验证码错误");
                return View();
            }
            else
            {
                string role = Request.Form["shenfen"];
                if (role == "1")  //管理员
                {
                    if (Admin(username,password))
                    {
                        //return Content("");
                        return  RedirectToAction("Index","DashBoard");
                    }
                    ModelState.AddModelError("", "账号或密码错误");
                }
                else if (role == "2")  //教师
                {
                    if (Teacher(username, password))
                    {
                        return RedirectToAction("Index", "Borrows");

                    }
                    ModelState.AddModelError("", "账号或密码错误");
                }
                else if (role == "3")  //学生
                {
                    if (Student(username, password))
                    {
                        return RedirectToAction("Index", "Borrows");
                    }
                    ModelState.AddModelError("", "账号或密码错误");
                }
                else
                {
                    ModelState.AddModelError("", "请选择身份");
                }
            }
            return View();
        }

        //管理员登录验证的方法
        protected bool Admin(string AdminUserName, string AdminPassword)
        {

            using (BooksSystemContext db = new BooksSystemContext())
            {
                var a = (from p in db.Admins where p.AdminUserName == AdminUserName && p.AdminPassword == AdminPassword select p).FirstOrDefault();
                if (a == null)
                {
                    return false;
                }
                else
                {

                    //Session.Clear();
                    Session["role"] = "Admin";
                    Session["Admin"] = a;
                    FormsAuthentication.SetAuthCookie(AdminUserName, false);
                    return true;
                }
            }
        }
        //教师登录验证的方法
        protected bool Teacher(string AdminUserName, string AdminPassword)
        {

            using (BooksSystemContext db = new BooksSystemContext())
            {
                var t = (from p in db.Teachers where (p.TeaIdCard == AdminUserName && p.TeaPwd == AdminPassword) || (p.TeaJobNum == AdminUserName && p.TeaPwd == AdminPassword) select p).FirstOrDefault();

                if (t == null)
                {
                    return false;
                }
                else
                {
                    Session.Clear();
                    Session["role"] = "Teacher";
                    Session["Teacher"] = t;
                    FormsAuthentication.SetAuthCookie(AdminUserName, false);
                    return true;
                }
            }
        }
        //学生登录验证的方法
        protected bool Student(string AdminUserName, string AdminPassword)
        {

            using (BooksSystemContext db = new BooksSystemContext())
            {
                var s = (from p in db.Students where (p.StuIdCard == AdminUserName && p.StuPwd == AdminPassword) || (p.StuNum == AdminUserName && p.StuPwd == AdminPassword) select p).FirstOrDefault();

                if (s == null)
                {
                    return false;
                }
                else
                {
                    //Session.Clear();
                    Session["role"] = "Student";
                    Session["Student"] = s;
                    FormsAuthentication.SetAuthCookie(AdminUserName, false);
                    return true;
                }
            }
        }



        /// <summary>
        /// 生成验证码的图片
        /// </summary>
        /// <param name="validateCode"></param>
        /// <returns></returns>
        public byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        //验证码的操作
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }

        // GET: /Admins/

        public ActionResult Index(int id=1)
        {
            var model = db.Admins.OrderByDescending(a => a.AdminId).ToPagedList(id, 10);
            if (Request.IsAjaxRequest())
                return PartialView("_AdminList", model);
            return View(model);
        }

        // GET: /Admins/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Admin admin = db.Admins.Find(id);
            if (admin == null)
            {
                return HttpNotFound();
            }
            return View(admin);
        }

        // GET: /Admins/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Admins/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="AdminId,AdminName,AdminUserName,AdminPassword,IsRoot,AuthoPwd,LoginTime,AdminPhone")] Admin admin)
        {
            admin.IsRoot = 0;
            if (ModelState.IsValid)
            {
                db.Admins.Add(admin);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(admin);
        }

        // GET: /Admins/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Admin admin = db.Admins.Find(id);
            if (admin == null)
            {
                return HttpNotFound();
            }
            return View(admin);
        }

        // POST: /Admins/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="AdminId,AdminName,AdminUserName,AdminPassword,IsRoot,AuthoPwd,LoginTime,AdminPhone")] Admin admin)
        {
            if (ModelState.IsValid)
            {
                db.Entry(admin).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(admin);
        }

        // GET: /Admins/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Admin admin = db.Admins.Find(id);
            if (admin == null)
            {
                return HttpNotFound();
            }
            return View(admin);
        }

        // POST: /Admins/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Admin admin = db.Admins.Find(id);
            db.Admins.Remove(admin);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
